﻿using System;
using System.Web;
using ExpertPdf.HtmlToPdf;
using Microsoft.SharePoint;

namespace CKS.EBE.API
{
    class PDF
    {
        private readonly string _PostTitle;
        private readonly byte[] _DownloadPDF;

        public PDF(SPListItem item, SPWeb web)
        {
            var itemURL = string.Format("{0}/{1}?ID={2}", web.Url, item.ParentList.Forms[PAGETYPE.PAGE_DISPLAYFORM].Url, item.ID);
            _PostTitle = item.Title;

            var converter = new PdfConverter {PageWidth = 0, AvoidImageBreak = true};
            converter.PdfDocumentInfo.AuthorName = new SPFieldUserValue(web, Convert.ToString(item[SPBuiltInFieldId.Author])).LookupValue;
            converter.PdfDocumentInfo.Title = item.Title;
            converter.PdfDocumentInfo.CreatedDate = DateTime.Now;
            if (BlogContext.Current.Settings.PDFExportLicenseKey != null && BlogContext.Current.Settings.PDFExportLicenseKey.Length > 14)
            {
                // apply license key, if it was entered in the blog settings
                converter.LicenseKey = BlogContext.Current.Settings.PDFExportLicenseKey;
            }
            converter.PdfDocumentOptions.AutoSizePdfPage = true;
            _DownloadPDF = converter.GetPdfBytesFromUrl(itemURL);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        internal void DownloadFile(HttpContext context)
        {
            HttpResponse Response = context.Response;
            string outputFileName = _PostTitle + ".pdf";
            try
            {
                Response.ContentType = "application/octet-stream";
                Response.AddHeader("Content-Disposition", "attachment; filename=\"" + outputFileName + "\"");
                Response.AddHeader("Content-Length", _DownloadPDF.Length.ToString());

                Response.OutputStream.Write(_DownloadPDF, 0, _DownloadPDF.Length);
            }
            catch (Exception ex)
            {
                // Trap the error, if any.
                context.Response.ContentType = "text/plain";
                context.Response.Write(string.Format("Error:\r\n{0}", ex));
            }
        }
    }
}
